package edu.westga.vocalengineer.audio;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

import edu.westga.vocalengineer.audio.gui.IGuiTransform;
import edu.westga.vocalengineer.audio.transforms.ITransform;

/***
 * AudioData A class to maintain sound data and apply transforms.
 * 
 * @author Matthew Shane Farmer
 * 
 */
public class AudioData extends Thread {
	private String filename;
	private Position curPosition;
	private AudioInputStream audioInputStream;
	private AudioFormat format;

	private final int EXTERNAL_BUFFER_SIZE = 524288; // 128Kb
	private boolean stopRequested;

	enum Position {
		LEFT, RIGHT, NORMAL
	};

	public AudioData(String wavfile) {
		filename = wavfile;
		curPosition = Position.NORMAL;
		File soundFile = new File(filename);
		if (!soundFile.exists()) {
			System.err.println("Wave file not found: " + filename);
			return;
		}

		try {
			audioInputStream = AudioSystem.getAudioInputStream(soundFile);
		} catch (UnsupportedAudioFileException e1) {
			e1.printStackTrace();
			return;
		} catch (IOException e1) {
			e1.printStackTrace();
			return;
		}

		format = audioInputStream.getFormat();
	}

	public AudioData(AudioInputStream newAudioInputStream)
	{
		audioInputStream = newAudioInputStream;
		curPosition = Position.NORMAL;
		format = audioInputStream.getFormat();
	}
	
	public AudioData(byte[] data, AudioFormat newFormat)
	{
		format = newFormat;
		curPosition = Position.NORMAL;
		applyNewBuffer(AudioTools.convertByteArrayToSamples(data));
	}

	
	public void run() {
		stopRequested = false;
		SourceDataLine auline = null;
		DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
		try {
			auline = (SourceDataLine) AudioSystem.getLine(info);
			auline.open(format);
		} catch (LineUnavailableException e) {
			e.printStackTrace();
			return;
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}

		if (auline.isControlSupported(FloatControl.Type.PAN)) {
			FloatControl pan = (FloatControl) auline
					.getControl(FloatControl.Type.PAN);
			if (curPosition == Position.RIGHT)
				pan.setValue(1.0f);
			else if (curPosition == Position.LEFT)
				pan.setValue(-1.0f);
		}

		auline.start();
		int nBytesRead = 0;
		byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];

		try {
			while ((nBytesRead != -1) && !stopRequested) {
				nBytesRead = audioInputStream.read(abData, 0, 256);
				if (nBytesRead >= 0)
					auline.write(abData, 0, nBytesRead);
			}
		} catch (IOException e) {
			e.printStackTrace();
			return;
		} finally {
			auline.drain();
			auline.close();
		}

	}

	public void applyTransform(ITransform transform) {
		applyNewBuffer(transform.execute(getSamples()));
	}

	// return a pointer to an array of individual samples
	private short[] getSamples() {
		int length = (int) (audioInputStream.getFrameLength() * format
				.getFrameSize());

		// dump entire stream
		byte[] samples = new byte[length];
		DataInputStream is = new DataInputStream(audioInputStream);
		try {
			is.readFully(samples);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		
		
		// done, return
		return AudioTools.convertByteArrayToSamples(samples);
	}
	
	// replace the audiostream object with a new one created from stream data
	// ASSUMES NEW DATA IS IN SAME FORMAT AS OLD
	private void applyNewBuffer(short[] samples) {
		byte[] buffer = AudioTools.convertSamplesToByteArray(samples);
		ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
		long length = (long)(buffer.length / format.getFrameSize());
		audioInputStream = new AudioInputStream(bais, format, length);
	}

	public void applyGuiTransform(IGuiTransform igt) {
		applyNewBuffer(igt.exectueWithGuiOptions(getSamples()));
	}

	public void requestStop() {
		stopRequested = true;		
	}

}
